use crate::capi::{
    iot_err_code_e, iot_err_code_e_RC_FAIL, iot_err_code_e_RC_INVALID_PARAMS, iot_err_code_e_RC_OK,
    server_address_t,
};
use crate::gslb::{get_servers_v2, GSLB};
use core::ffi::{c_char, c_uint};
use embed_std::errorln;
use embed_std::util::cstr_to_str;

#[no_mangle]
pub extern "C" fn get_servers_from_gslb(
    host: *const c_char,
    product_code: *const c_char,
    device_uid: *const c_char,
    addrs: *mut server_address_t,
    count: u8,
    act_count: *mut u8,
) -> iot_err_code_e {
    get_servers_from_gslb_v2(
        host,
        product_code,
        device_uid,
        addrs,
        count,
        act_count,
        0x1 | 0x2,
    )
}

#[no_mangle]
pub extern "C" fn get_servers_from_gslb_v2(
    host: *const c_char,
    product_code: *const c_char,
    device_uid: *const c_char,
    addrs: *mut server_address_t,
    count: u8,
    act_count: *mut u8,
    flags: c_uint,
) -> iot_err_code_e {
    if product_code.is_null() || device_uid.is_null() || addrs.is_null() || count == 0 {
        return iot_err_code_e_RC_INVALID_PARAMS;
    }
    let gslb_addr = if host.is_null() {
        GSLB
    } else {
        cstr_to_str(host)
    };
    let pc = cstr_to_str(product_code);
    let duid = cstr_to_str(device_uid);
    match get_servers_v2(gslb_addr, pc, duid, flags) {
        Ok(servers) => {
            let mut num = 0;
            for i in 0..servers.len() {
                if num >= count {
                    break;
                }
                unsafe {
                    core::ptr::write(
                        addrs.offset(num as isize),
                        server_address_t::from(&servers[i]),
                    );
                }
                num += 1;
            }
            if !act_count.is_null() {
                unsafe {
                    *act_count = num as u8;
                }
            }
            iot_err_code_e_RC_OK
        }
        Err(e) => {
            errorln!("get_servers_from_gslb failed: {}", e);
            iot_err_code_e_RC_FAIL
        }
    }
}
